//
//  YYPersonageSubscribeVC.m
//  drivingSchool
//
//  Created by 子yu 刘 on 2018/8/18.
//  Copyright © 2018年 子yu 刘. All rights reserved.
//

#import "YYPersonageSubscribeVC.h"
#import "YYTakeCarWayVC.h"
#import "YYInvoiceVC.h"
#import "YYPickerView.h"
#import "YYUploadVC.h"
#import "YYPayVC.h"

@interface YYPersonageSubscribeVC ()
@property (nonatomic,strong)NSArray * dateArr;
@property (nonatomic,strong)NSArray * timeArr;
@property (nonatomic ,copy)NSString * invoice_name;
@property (nonatomic ,copy)NSString * invoice_number;
@property (nonatomic ,copy)NSString * adress;
@property (nonatomic ,copy)NSString * img;
@property (nonatomic ,copy)NSString * inspect_type;
@property (nonatomic ,copy)NSString * time_id;
@property (nonatomic ,copy)NSString * time_type;
@property (nonatomic ,copy)NSString * is_invoice;
@property (nonatomic ,copy)NSString * invoice_type;

@end

@implementation YYPersonageSubscribeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _inspect_type = @"0";
    _is_invoice = @"0";
    _invoice_type = @"0";
    _invoice_name = @"0";
    _invoice_number = @"0";
    _adress = @"0";
    [self getData];
}

- (void)getData{
    [RequestOperationManager personalInspectTime_success:^(id result) {
        if (DEF_REQ_SUCCESS) {
            self.dateArr = result[@"data"];
        }
    } failture:^(NSError *error) {
        
    }];
}

- (IBAction)chooseWay:(id)sender {
    YYTakeCarWayVC * takeWay = (YYTakeCarWayVC *)[CFUtility getVC:@"YYTakeCarWayVC" Storyboard:MINE];
    MJWeakSelf;
    [takeWay setBlock:^(NSString *type, NSString *adress) {
        weakSelf.inspect_type = type;
        if ([type isEqualToString:@"0"]) {
            weakSelf.adress = @"";
            [weakSelf.btnWay setTitle:@"个人送达" forState:UIControlStateNormal];
        }else if ([type isEqualToString:@"1"]){
            weakSelf.adress = adress;
            [weakSelf.btnWay setTitle:@"上门取车" forState:UIControlStateNormal];
        }
    }];
    [self.navigationController pushViewController:takeWay animated:YES];
}
- (IBAction)chooseDate:(id)sender {
    if (self.dateArr.count<=0) {
        return;
    }
    YYPickerView * pickerView = [[YYPickerView alloc] init];
    NSMutableArray * date = [NSMutableArray arrayWithCapacity:0];
    for (NSDictionary * dic in self.dateArr) {
        [date addObject:dic[@"time"]];
    }
    
    pickerView.dataArr = date;
    MJWeakSelf;
    pickerView.block = ^(NSInteger index) {
        if ([weakSelf.dateArr[index][@"status"] intValue] != 0) {
            [AlertUtil alertMessage:@"当前为节假日不可选"];
            return ;
        }
        weakSelf.lbDate.text = date[index];
        weakSelf.timeArr = weakSelf.dateArr[index][@"list"];
        weakSelf.time_type = weakSelf.dateArr[index][@"type"];
    };
    [self.view addSubview:pickerView];
    [pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
}
- (IBAction)chooseTime:(id)sender {
    if (!_timeArr) {
        [AlertUtil alertMessage:@"请先选择日期"];
        return;
    }
    YYPickerView * pickerView = [[YYPickerView alloc] init];
    NSMutableArray * timeArr = [NSMutableArray arrayWithCapacity:0];
    for (NSDictionary * dict in self.timeArr) {
        [timeArr addObject:[NSString stringWithFormat:@"%@-%@",dict[@"stime"],dict[@"etime"]]];
    }
    pickerView.dataArr = timeArr;
    MJWeakSelf;
    pickerView.block = ^(NSInteger index) {
        [ RequestOperationManager dateIsReserve_id: weakSelf.timeArr[index][@"id"] success:^(id result) {
            if (DEF_REQ_SUCCESS) {
                weakSelf.lbTime.text = timeArr[index];
                weakSelf.time_id = weakSelf.timeArr[index][@"id"];
            }
        } failture:^(NSError *error) {
            
        }];
    };
    [self.view addSubview:pickerView];
    [pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

- (IBAction)chooseType:(id)sender {
    YYInvoiceVC * invoice = (YYInvoiceVC *)[CFUtility getVC:@"YYInvoiceVC" Storyboard:HOME];
    MJWeakSelf;
    invoice.block = ^(NSString *type, NSString *title, NSString *name) {
        weakSelf.invoice_name = name;
        weakSelf.invoice_number = title;
        weakSelf.inspect_type = type;
        if ([type isEqualToString:@"0"]) {
            [weakSelf.btnType setTitle:@"无需发票" forState:UIControlStateNormal];
            weakSelf.is_invoice = @"0";
        }else if ([type isEqualToString:@"1"]) {
            [weakSelf.btnType setTitle:@"个人发票" forState:UIControlStateNormal];
            weakSelf.is_invoice = @"1";
        }else if ([type isEqualToString:@"2"]) {
            weakSelf.is_invoice = @"1";
            [weakSelf.btnType setTitle:@"公司发票" forState:UIControlStateNormal];
        }
        
    };
    [self.navigationController pushViewController:invoice animated:YES];
}
- (IBAction)uploadImage:(id)sender {
    YYUploadVC * upload = (YYUploadVC *)[CFUtility getVC:@"YYUploadVC" Storyboard:MINE];
    upload.urlStr = _img;
    
    MJWeakSelf;
    upload.block = ^(NSString *image) {
        weakSelf.img = image;
        [weakSelf.btnUploading setTitle:@"已上传" forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:upload animated:YES];
}

- (IBAction)subscribe:(id)sender {
    if (self.tfName.text.length == 0) {
        [AlertUtil alertMessage:@"请输入您的姓名"];
        return;
    }
    if (self.tfPhone.text.length == 0) {
        [AlertUtil alertMessage:@"请输入您的手机号"];
        return;
    }
    if (self.tfCarNum.text.length == 0) {
        [AlertUtil alertMessage:@"请输入车牌号码"];
        return;
    }
    if (!_time_id) {
        [AlertUtil alertMessage:@"请选择时间"];
        return;
    }
    if (!_img) {
        [AlertUtil alertMessage:@"请上传您的行驶证"];
        return;
    }
    
    NSDictionary * parm = @{
                            @"uid":DEF_UID,
                            @"inspect_name":self.tfName.text,
                            @"inspect_phone":self.tfPhone.text,
                            @"plate":self.tfCarNum.text,
                            @"inspect_type":_inspect_type,
                            @"address":_adress,
                            @"time_id":_time_id,
                            @"time_type":_time_type,
                            @"is_invoice":_is_invoice,
                            @"invoice_type":_inspect_type,
                            @"invoice_name":_invoice_name,
                            @"invoice_number":_invoice_number,
                            @"img":_img,
                            @"source":@"iOS"
                            };
    
    YYPayVC * pay = (YYPayVC *)[CFUtility getVC:@"YYPayVC" Storyboard:HOME];
    pay.isHidden = YES;
    pay.money = self.price;
    // pay.parme = dict;
    pay.payBlock = ^(NSString *type) {
        if ([type isEqualToString:@"0"]) {
            [RequestOperationManager checkCar_parm:parm success:^(id result) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (DEF_REQ_SUCCESS) {
                    [self aliPayWithSign:result[@"data"]];
                }else{
                    [AlertUtil alertMessage:result[@"msg"]];
                }
            } failture:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
            
        }else{
            [RequestOperationManager checkCarWXPay_parm:parm success:^(id result) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (DEF_REQ_SUCCESS) {
                    [self wechatPayWithResponse:result[@"data"]];
                }else{
                    [AlertUtil alertMessage:result[@"msg"]];
                }
            } failture:^(NSError *error) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }
        
    };
    [self.navigationController pushViewController:pay animated:YES];
    
}

-(NSArray *)dateArr{
    if (!_dateArr) {
        _dateArr = [NSArray array];
    }
    return _dateArr;
}

-(NSArray *)timeArr{
    if (!_timeArr) {
        _timeArr = [NSArray array];
    }
    return _timeArr;
}

- (void)wechatPayWithResponse:(NSDictionary *)response {
    PayReq* req  = [[PayReq alloc] init];
    req.partnerId = response[@"partnerid"];
    req.prepayId= response[@"prepayid"];
    req.package = response[@"package"];
    req.nonceStr= response[@"noncestr"];
    req.timeStamp= [response[@"timestamp"] intValue];
    req.sign=response[@"sign"];
    [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        
        if (errCode == FLErrCodeSuccess) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
        }
    }];
}

- (void)aliPayWithSign:(NSString * )sign{
    /**
     *  @author gitKong
     *
     *  来自支付宝文档数据
     */
    
    [FLPAYMANAGER fl_payWithOrderMessage:sign callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        if (resultDic&&[resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
            
        }
        
    }];
    
    
}


- (NSString *)jumpToBizPay {
    //============================================================
    /**
     *  @author Clarence
     *
     *  来自微信文档数据
     */
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                
                [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
                    NSLog(@"errCode = %zd,errStr = %@",errCode,errStr);
                }];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                return @"";
            }else{
                return [dict objectForKey:@"retmsg"];
            }
        }else{
            return @"服务器返回错误，未获取到json对象";
        }
    }else{
        return @"服务器返回错误";
    }
    
}

@end
